#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef struct {
    int size; /* 当前元素个数 */
    int *data; /* 数据 */
    int capacity;  /* 当前最大能存储的个数 */
} Vector;

void show(Vector *v)
{
    for (int i = 0; i < v->size; i++) {
        printf("%d ", v->data[i]);
    }
    printf("\n");
}

int init(Vector *v)
{
    v->size = 0;
    v->capacity = 256;
    v->data = (int *)malloc(v->capacity * sizeof(int));
    return 0;
}

int destroy(Vector *v)
{
    v->size = 0;
    v->capacity = 0;
    free(v->data);
    return 0;
}

int push_back(Vector *v, int data)
{
    if (v->size == v->capacity) {
        int *tmp = (int *)malloc(2 * v->capacity * sizeof(int));
        memcpy(tmp, v->data, v->capacity * sizeof(int));
        free(v->data);
        v->data = tmp;
        v->capacity *= 2;
    }

    v->data[v->size] = data;
    v->size++;
    return 0;
}

int pop_back(Vector *v)
{
    if (v->size == 0) {
        return 1;
    }

    v->size--;
    return 0;
}

int pop_head(Vector *v)
{    
    if (v->size == 0) {
        return 1;
    }

    memmove(v->data, v->data + 1, (v->size - 1) * sizeof(int));
    v->size--;
    return 0;
}

int insert(Vector *v, int pos, int data)
{
    if (pos >= v->size) {
        return push_back(v, data);
    }

    if (v->size == v->capacity) {
        int *tmp = (int *)malloc(2 * v->capacity * sizeof(int));
        memcpy(tmp, v->data, v->capacity * sizeof(int));
        free(v->data);
        v->data = tmp;
        v->capacity *= 2;
    }

    memmove(v->data + pos + 1, v->data + pos, (v->size - pos) * sizeof(int));
    v->data[pos] = data;
    v->size++;
    return 0;
}

int remove(Vector *v, int pos)
{
    if (v->size == 0) {
        return 1;
    }

    if (pos >= v->size) {
        return 1;
    }

    memmove(v->data + pos, v->data + pos + 1, (v->size - pos - 1) * sizeof(int));
    v->size--;
    return 0;
}

void testVector(void)
{
    Vector v;
    init(&v);

    for (int i = 0; i < 10; i++) {
        push_back(&v, i);
    }

    for (int i = 0; i < 5; i++) {
        pop_head(&v);
    }

    for (int i = 0; i < 5; i++) {
        pop_back(&v);
    }

    push_back(&v, 1);
    push_back(&v, 2);
    push_back(&v, 3);
    push_back(&v, 4);
    remove(&v, 1);
    insert(&v, 1, 2);
    insert(&v, 3, 10);
    insert(&v, 5, 11);

    show(&v);
    destroy(&v);
}

int main(int argc, char const *argv[])
{
    testVector();
    return 0;
}
